package com.owbtgad.common.base

import android.os.Bundle
import android.view.View
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * 使用 DataBind 并使用ViewModel
 * @param <VDB>
 * @param <VM> 继承BaseViewModel
 */
abstract class BaseMFragment<VDB : ViewDataBinding,VM : BaseViewModel>: BaseDFragment<VDB>(){
    protected lateinit var mViewModel: VM
    private fun isViewModel() = ::mViewModel.isInitialized
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        createViewModel()
    }

    open fun createViewModel() {
        if (mViewModel == null) {
            val type = javaClass.genericSuperclass
            if (type is ParameterizedType){
                type.actualTypeArguments[1]?.let {
                    mViewModel = ViewModelProvider(this).get(it as Class<VM>)
                }
            }
        }
    }
}